import {designPage} from "@peryl/react-compose";
import {useTableOption} from "./useTableOption";
import {PlainObject} from "@peryl/utils/event";
import {notNull} from "@peryl/utils/notNull";
import {http} from "./http";
import {$dialog, AutoTable, PlcDate, PlcDraggier, PlcInput} from "plain-design";

export const openOptionValueManager = (ov: string, config?: { title?: string, onClose?: () => void }) => {
  const OptionValueManager = designPage(() => {

    const option = useTableOption({
      url: '/ov',
      fill: true,
      pageSize: 9999,
      param: {
        orders: [{ field: "seq", desc: true }],
        filters: [{ field: 'type', value: ov, operator: '=', id: 'option_value_filter_type' }]
      },
      defaultNewRow: (): any => {
        const currentFistRow: PlainObject | undefined = option.state.list[0];
        return {
          type: ov,
          comment: currentFistRow?.comment,
          seq: notNull(currentFistRow?.seq, 1),
        };
      },
    });

    const handler = {
      onSortChange: async () => {
        const updateList: any[] = [];
        const len = option.state.list.length;
        option.state.list.forEach((item, index) => {
          const seq = len - index;
          if (item.seq !== seq) {updateList.push({ ...item, seq });}
        });
        const resp = await http.post<{ result: any }>('/ov/batchUpdate', { rows: updateList, updateFields: ['seq'] });
        console.log(resp);
      },
    };

    return () => (
      <AutoTable option={option}>
        <PlcDraggier v-model={option.state.list} onChange={handler.onSortChange}/>
        <PlcInput title="显示值" field="name"/>
        <PlcInput title="代码" field="code"/>
        <PlcInput title="类型" field="type"/>
        <PlcDate title="创建时间" field="createdAt" hideInForm width={180} editable={false} datetime/>
        <PlcInput title="说明" field="comment"/>
      </AutoTable>
    );
  });
  $dialog({
    title: config?.title || '管理选项值',
    position: 'right',
    width: 1000,
    noContentPadding: true,
    onClose: config?.onClose,
    render: () => (<OptionValueManager/>)
  });
};
